<template>
  <div>
    <el-card>
      <div class="mb-4">
        <el-button type="primary" @click="handleAdd">新增排班</el-button>
      </div>
      
      <el-table :data="scheduleList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户">
          <template #default="{ row }">
            {{ userFormatter(row.userId) }}
          </template>
        </el-table-column>
        <el-table-column prop="shiftDate" label="排班日期" />
        <el-table-column prop="shiftType" label="班次类型">
          <template #default="{ row }">
            {{ shiftTypeText(row.shiftType) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="formRef">
        <!-- 修改后的表单部分 -->
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户">
            <el-option 
              v-for="user in userMap" 
              :key="user.id" 
              :label="user.userName" 
              :value="user.id" />
        </el-select>
        </el-form-item>
        
        <!-- 确保rules中的userId验证规则保持不变 -->
        <el-form-item label="排班日期" prop="shiftDate">
          <el-date-picker 
            v-model="form.shiftDate" 
            type="date" 
            placeholder="选择排班日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="班次类型" prop="shiftType">
          <el-select v-model="form.shiftType" placeholder="请选择班次类型">
            <el-option label="早班" :value="0" />
            <el-option label="晚班" :value="1" />
            <el-option label="夜班" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  listSchedule, 
  addSchedule, 
  updateSchedule, 
  delSchedule 
} from '@/api/schedule'
import { listUsertable } from '@/api/usertable'

const scheduleList = ref([])
const userMap = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref(null)

const form = reactive({
  id: null,
  userId: null,
  shiftDate: '',
  shiftType: null
})

const rules = {
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  shiftDate: [{ required: true, message: '请选择排班日期', trigger: 'change' }],
  shiftType: [{ required: true, message: '请选择班次类型', trigger: 'change' }]
}

// 班次类型文本转换
const shiftTypeText = (type) => {
  const map = {
    0: '早班',
    1: '晚班',
    2: '夜班'
  }
  return map[type] || '未知'
}

// 获取排班记录列表
const getScheduleList = async () => {
  try {
    const response = await listSchedule()
    if (response) {
      scheduleList.value = response
    } else {
      ElMessage.error('获取排班列表失败: 数据格式异常')
    }
  } catch (error) {
    ElMessage.error(`获取排班列表失败: ${error.message}`)
  }
}

// 新增排班记录
const handleAdd = () => {
  dialogTitle.value = '新增排班'
  isAdd.value = true
  Object.assign(form, {
    id: null,
    userId: null,
    shiftDate: '',
    shiftType: null
  })
  dialogVisible.value = true
}

// 编辑排班记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑排班'
  isAdd.value = false
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除排班记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该排班记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delSchedule(row.id)
    ElMessage.success('删除成功')
    getScheduleList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  try {
    if (isAdd.value) {
      await addSchedule(form)
      ElMessage.success('新增成功')
    } else {
      await updateSchedule(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getScheduleList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 用户ID转名称
const userFormatter = (value) => {
  const user = userMap.value.find((item) => item.id == value)
  return user ? user.userName : value
}

// 修改后的获取用户数据方法
const fetchUsers = async () => {
  try {
    const response = await listUsertable({ roleId: 3 }) // 添加roleId参数
    if (response) {
      userMap.value = response
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
  }
}

onMounted(() => {
  getScheduleList()
  fetchUsers()
})
</script>